//
//  WithdrawViewController.m
//  Molian
//
//  Created by wansong on 4/9/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//

#import "WithdrawViewController.h"
#import "WalletRecordViewController.h"

#define NUMBERS @"0123456789\n"
@interface WithdrawViewController ()


@property (nonatomic, strong) UITextField *alipayField;

@property (nonatomic, strong) UITextField *moneyField;
@property (nonatomic, strong) UILabel *changeLabel;

@end

@implementation WithdrawViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"提现";
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    // 从导航条以下开始计算
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    // 金额显示
    UIView *moneyView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, DeviceWidth, 60)];
    moneyView.clipsToBounds = YES;
    moneyView.backgroundColor = [UIColor whiteColor];
    [moneyView.layer setBorderWidth:0.5];
    [moneyView.layer setBorderColor:RGBA(229, 229, 229, 1).CGColor];
    [self.view addSubview:moneyView];
    
    UILabel *titleLable = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, 100, 30)];
    titleLable.font = [UIFont fontWithName:FontName size:16];
    titleLable.textAlignment = NSTextAlignmentLeft;
    titleLable.textColor = [UIColor blackColor];
    titleLable.text = @"钱包余额";
    [moneyView addSubview:titleLable];
    
    // 余额值
    UILabel*moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(DeviceWidth-120, 15, 100, 30)];
    moneyLabel.font = [UIFont fontWithName:FontName size:14];
    moneyLabel.textAlignment = NSTextAlignmentRight;
    moneyLabel.textColor = [UIColor grayColor];
    moneyLabel.text = [NSString stringWithFormat:@"%.0f 时光",([MLUser currentUser].balance*10)];
    [moneyView addSubview:moneyLabel];
    
    
    UIView *withdrawView = [[UIView alloc]initWithFrame:CGRectMake(0, 100, DeviceWidth, 180+55)];
    withdrawView.clipsToBounds = YES;
    withdrawView.backgroundColor = [UIColor whiteColor];
    [withdrawView.layer setBorderWidth:0.5];
    [withdrawView.layer setBorderColor:RGBA(229, 229, 229, 1).CGColor];
    [self.view addSubview:withdrawView];
    
    
    self.alipayField = [[UITextField alloc]initWithFrame:CGRectMake(15, 15, DeviceWidth-30, 45)];
    self.alipayField.layer.masksToBounds = YES;
    [self.alipayField.layer setCornerRadius:22.5f];
    self.alipayField.placeholder = @"支付宝账户";
    [self.alipayField.layer setBorderWidth:0.5];
    [self.alipayField.layer setBorderColor:UIColorFromRGB(0xcccccc).CGColor];
    self.alipayField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];//缩进
    self.alipayField.leftViewMode  = UITextFieldViewModeAlways;
    [withdrawView addSubview:self.alipayField];
    
    self.moneyField = [[UITextField alloc]initWithFrame:CGRectMake(15, 75, DeviceWidth-30, 45)];
    self.moneyField.layer.masksToBounds = YES;
    [self.moneyField.layer setCornerRadius:22.5f];
    self.moneyField.placeholder = @"提现金额(元)";
    self.moneyField.keyboardType = UIKeyboardTypeNumberPad;
    [self.moneyField.layer setBorderWidth:0.5];
    [self.moneyField.layer setBorderColor:UIColorFromRGB(0xcccccc).CGColor];
    self.moneyField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
     [self.moneyField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.moneyField.leftViewMode  = UITextFieldViewModeAlways;
    [withdrawView addSubview:self.moneyField];
    
    UILabel *tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 135, DeviceWidth-60, 19)];
    tipsLabel.font = [UIFont fontWithName:FontName size:14];
    tipsLabel.textColor = UIColorFromRGB(0x999999);
    tipsLabel.text = @"10时光=1元,提现金额不能少于50元";
    tipsLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [withdrawView addSubview:tipsLabel];
    
    self.changeLabel = [[UILabel alloc]initWithFrame:CGRectMake(DeviceWidth-30-100, 154, 100, 19)];
    self.changeLabel .font = [UIFont fontWithName:FontName size:14];
    self.changeLabel .textColor = RGBA(88, 198, 83, 1);
    self.changeLabel .text = @"xxx元";
    self.changeLabel.textAlignment = NSTextAlignmentRight;
    self.changeLabel .lineBreakMode = NSLineBreakByWordWrapping;
    [withdrawView addSubview:self.changeLabel ];
    
    UILabel *tipsLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(30, 154, DeviceWidth-160, 19)];
    tipsLabel1.font = [UIFont fontWithName:FontName size:14];
    tipsLabel1.textColor = UIColorFromRGB(0x999999);
    tipsLabel1.text = @"实际到账金额";
    tipsLabel1.lineBreakMode = NSLineBreakByWordWrapping;
    [withdrawView addSubview:tipsLabel1];
    UILabel *tipsLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(30, 173, DeviceWidth-60, 55)];
    tipsLabel2.numberOfLines = 0;
    tipsLabel2.font = [UIFont fontWithName:FontName size:14];
    tipsLabel2.textColor = UIColorFromRGB(0x999999);
    tipsLabel2.text = @"(因服务器和短信费用压力增大,自今日起,我们提现将收取15%的提现手续费,提现金额不能少于50元,三到五个工作日到账)";
    tipsLabel2.lineBreakMode = NSLineBreakByWordWrapping;
    [withdrawView addSubview:tipsLabel2];
    
    
    
    // 提交审核按钮
    UIButton *withdrawBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 330+50, DeviceWidth-30, 45)];
    withdrawBtn.layer.masksToBounds = YES;
    [withdrawBtn.layer setCornerRadius:22.5f];
    [withdrawBtn setBackgroundImage:[UIImage imageWithColor:RGBA(242, 206, 62, 1)] forState:UIControlStateNormal];
    [withdrawBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [withdrawBtn setTitle:@"提交" forState:UIControlStateNormal];
    withdrawBtn.titleLabel.font = [UIFont fontWithName:FontName size:16];
    [withdrawBtn addTarget:self action:@selector(submitWithdraw) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:withdrawBtn];

    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(returnKeyBorad)]];
    
    UIButton *ringetBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [ringetBt sizeToFit];
    [ringetBt setTitle:@"提现记录" forState:UIControlStateNormal];
    ringetBt.titleLabel.font = kFont(15);
    ringetBt.frame = CGRectMake(0, 0, 60, 30);
    ringetBt.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [ringetBt addTarget:self action:@selector(clickRingetBt) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *ringetBatBt = [[UIBarButtonItem alloc] initWithCustomView:ringetBt];
    self.navigationItem.rightBarButtonItem = ringetBatBt;
    
}
//文字改变
- (void)textFieldDidChange:(UITextField *)textfField
{
    if(textfField.text.length>0){
        CGFloat a = [textfField.text floatValue];
        CGFloat b = a*0.85;
        self.changeLabel .text = [NSString stringWithFormat:@"%.2f元",b];
    }else{
      self.changeLabel .text = @"xxx元";
    }
}
- (void)clickRingetBt
{
    
    WalletRecordViewController *walletRVC = [[WalletRecordViewController alloc] init];
    walletRVC.title = @"提现记录";
    [self.navigationController pushViewController:walletRVC animated:YES];
}
//回收键盘
-(void)returnKeyBorad
{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

#pragma mark - user interaction
// 去提现
- (void)submitWithdraw {
     MLUser *currentUser = [MLUser currentUser];
    [currentUser refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (!error) {
            //判断输入信息合法性
            BOOL isVerify = [self verifyAlipayText:self.alipayField.text andMoney:self.moneyField.text];
            if (isVerify) {
                
                AVQuery *q = [MLWithdraw query];
                [q whereKey:@"status" equalTo:[NSNumber numberWithInteger:MLWithdrawStatus_WAIT_PAY]];
                [q whereKey:@"user" equalTo:currentUser];
                [q findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    if (error||objects.count==0) {
                        MLWithdraw *withdraw = [MLWithdraw object];
                        withdraw.sum = [self.moneyField.text integerValue];
                        withdraw.status = MLWithdrawStatus_WAIT_PAY;
                        withdraw.alipay_account = self.alipayField.text;
                        withdraw.user = currentUser;
                        [withdraw saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                            if (succeeded) {
                                [AVAnalytics event:@"成功提现"]; // 通知服务器一个点击事件。
                                [HUD Prompt:@"申请提现成功请耐心等待审核"];
                                [self.navigationController popViewControllerAnimated:YES];
                            }else{
                                [HUD Prompt:@"请返回重试"];
                            }
                        }];
                    }else{
                        [HUD Prompt:@"请耐心等待上次审核结果"];
                    }
                }];
            }
        }else{
            [HUD Prompt:@"操作错误,请重新尝试"];
        }
    }];
}
- (BOOL)verifyAlipayText:(NSString *)alipayId andMoney:(NSString *)money{
    if (!alipayId||[alipayId isEqualToString:@""]) {
        [HUD Prompt:@"请输入支付宝账户"];
        return NO;
    }else if (!money||[money isEqualToString:@""]){
        [HUD Prompt:@"请输入提取金额"];
        return NO;
    }else if(![self isPureInt:money]||[money intValue]<50 ){
        //验证金额的合法性
        [HUD Prompt:@"请输入大于50的整数金额"];
        return NO;
    }else if    ([money floatValue]>[MLUser currentUser].balance){
        [HUD Prompt:@"余额不足"];
        return NO;
    }
    
    return YES;
}
//整形判断
- (BOOL)isPureInt:(NSString *)string{
    NSScanner *scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
@end
